package user

import (
	"encoding/json"
	"fmt"
	"github.com/gin-gonic/gin"
	"io/ioutil"
	"net/http"
	"net/url"
	"time"
	"zhuandan/data_source"
	"zhuandan/models"
)

func UserLoginywdcs(ctx *gin.Context) {
	json1 := KDRespBody{}
	ctx.ShouldBind(&json1)
	unionid := json1.Unionid

	data := httpPostFormuser(unionid)

	ctx.JSON(http.StatusOK, gin.H{
		"code":    0,
		"error":   0,
		"success": 200,
		"data":    data,
		"msg":     "ok",
	})
	return
}

func UserLoginywd(ctx *gin.Context) {
	json1 := KDRespBody{}
	ctx.ShouldBind(&json1)
	code := json1.Code
	pid := json1.Pid

	open := Accesstokenywd(code)
	//fmt.Println(open)
	//return
	openid := open.Openid
	unionid := open.Unionid
	dingyue := Userdingyue(openid)
	//	openid := open.Openid
	//unionid := open.Unionid
	if openid == "" {
		ctx.JSON(http.StatusOK, gin.H{
			"code":    300,
			"error":   1,
			"success": 400,
			"data":    "on",
			"msg":     "账号不存在",
		})
		return
	}

	reqip := ctx.ClientIP()

	//data := httpPostFormuser(unionid)
	//var weixin models.YwWeixin
	//data_source.OtherDb.Where("unionid = ?", unionid).First(&weixin)
	//fmt.Println(weixin)

	var user models.User
	data_source.Db.Where("unionid = ?", unionid).First(&user)
	if user.ID == 0 {
		weixinuser := Accesstokengzh(open.Openid, open.AccessToken)
		adduser := models.User{
			LoginTime:     time.Now().Unix(),
			LoginIp:       reqip,
			Ywdgzheopenid: openid,
			CreateTime:    time.Now().Unix(),
			LoginNum:      1,
			Logo:          weixinuser.Headimgurl,
			Nickname:      weixinuser.Nickname,
			Status:        1,
			Unionid:       unionid,
			Pid:           pid,
			Guanlian:      2,
			Identity:      1,
			Vip:           1,
			State:         1,
			Laiyuan:       2,
			Iflogin:       2,
			Bangwowa:      1,
			Dakefu:        1,
			Ifbuy:         1,
			Ywddingyue:    int64(dingyue.Subscribe) + 1,
			Accept:        2,
		}
		data_source.Db.Create(&adduser)
		adduser.Tuisong = 1
		ctx.JSON(http.StatusOK, gin.H{
			"code":    0,
			"error":   0,
			"success": 200,
			"data":    adduser,
			"msg":     "ok",
		})
		return
	} else {
		upuser := models.User{
			Ywdgzheopenid: openid,
			LoginTime:     time.Now().Unix(),
			LoginIp:       reqip,
			LoginNum:      user.LoginNum + 1,
			Ywddingyue:    int64(dingyue.Subscribe) + 1,
		}
		data_source.Db.Where("id = ?", user.ID).Updates(upuser)
		var tuisongshezhi []models.Tuisongshezhi
		data_source.Db.Where("uid = ?", user.ID).Where("state = 1").Find(&tuisongshezhi)
		if len(tuisongshezhi) == 0 {
			user.Tuisong = 1
		} else {
			user.Tuisong = 2
		}
		ctx.JSON(http.StatusOK, gin.H{
			"code":    0,
			"error":   0,
			"success": 200,
			"data":    user,
			"msg":     "ok",
		})
		return
	}
	//if weixin.ID == 0 {
	//
	//} else {
	//	if user.ID > 0 {
	//		upuser := models.User{
	//			Ywdgzheopenid: openid,
	//			LoginTime:     time.Now().Unix(),
	//			LoginIp:       reqip,
	//			Price:         weixin.Money,
	//			LoginNum:      user.LoginNum + 1,
	//			Ywddingyue:    int64(dingyue.Subscribe) + 1,
	//		}
	//		data_source.Db.Where("id = ?", user.ID).Updates(upuser)
	//		var tuisongshezhi []models.Tuisongshezhi
	//		data_source.Db.Where("uid = ?", user.ID).Where("state = 1").Find(&tuisongshezhi)
	//		if len(tuisongshezhi) == 0 {
	//			user.Tuisong = 1
	//		} else {
	//			user.Tuisong = 2
	//		}
	//		if user.Tongbuxiaofei == 1 {
	//			var xiaofei []models.YwAccountMoney
	//			data_source.OtherDb.Where("account_id = ?", weixin.ID).Find(&xiaofei)
	//
	//			var userpricenews []models.Userpricenew
	//			data_source.Db.Where("uid = ?", user.ID).Find(&userpricenews)
	//			var userpricenewadds []models.Userpricenew
	//			for _, x := range xiaofei {
	//				cunzai := 1
	//				for _, u := range userpricenews {
	//					if x.Ctime == u.Addtime {
	//						cunzai = 2
	//					}
	//				}
	//				if cunzai == 1 {
	//					userpricenewadd := models.Userpricenew{
	//						Uid:     user.ID,
	//						Addtime: x.Ctime,
	//						State:   int64(x.Type),
	//						Price:   x.Money,
	//						Title:   x.Memo,
	//						Dqprice: x.RemainMoney,
	//					}
	//					userpricenewadds = append(userpricenewadds, userpricenewadd)
	//				}
	//			}
	//			data_source.Db.Create(&userpricenewadds)
	//			data_source.Db.Model(&models.User{}).Where("id = ?", user.ID).Update("tongbuxiaofei", 2)
	//		}
	//		if user.Tongbudingdan == 1 {
	//			ordertongbu := models.Orderywdtongbu{
	//				Uid:   user.ID,
	//				Chuli: 1,
	//			}
	//			data_source.Db.Create(&ordertongbu)
	//			data_source.Db.Model(&models.User{}).Where("id = ?", user.ID).Update("tongbudingdan", 2)
	//		}
	//
	//		ctx.JSON(http.StatusOK, gin.H{
	//			"code":    0,
	//			"error":   0,
	//			"success": 200,
	//			"data":    user,
	//			"msg":     "ok",
	//		})
	//		return
	//
	//	} else {
	//
	//		adduser := models.User{
	//			LoginTime:     time.Now().Unix(),
	//			LoginIp:       reqip,
	//			Ywdgzheopenid: openid,
	//			CreateTime:    time.Now().Unix(),
	//			LoginNum:      1,
	//			Logo:          weixin.Headimgurl,
	//			Nickname:      weixin.Nickname,
	//			Status:        1,
	//			Unionid:       unionid,
	//			Phone:         weixin.Mobile,
	//			Price:         weixin.Money,
	//			Pid:           pid,
	//			Guanlian:      2,
	//			Identity:      1,
	//			Vip:           1,
	//			State:         1,
	//			Laiyuan:       2,
	//			Iflogin:       2,
	//			Dakefu:        1,
	//			Ifbuy:         1,
	//			Ywddingyue:    int64(dingyue.Subscribe) + 1,
	//			Accept:        1,
	//		}
	//		data_source.Db.Create(&adduser)
	//		if user.Tongbuxiaofei == 1 {
	//			var xiaofei []models.YwAccountMoney
	//			data_source.OtherDb.Where("account_id = ?", weixin.ID).Find(&xiaofei)
	//
	//			var userpricenews []models.Userpricenew
	//			data_source.Db.Where("uid = ?", adduser.ID).Find(&userpricenews)
	//			var userpricenewadds []models.Userpricenew
	//			for _, x := range xiaofei {
	//				cunzai := 1
	//				for _, u := range userpricenews {
	//					if x.Ctime == u.Addtime {
	//						cunzai = 2
	//					}
	//				}
	//				if cunzai == 1 {
	//					userpricenewadd := models.Userpricenew{
	//						Uid:     adduser.ID,
	//						Addtime: x.Ctime,
	//						State:   int64(x.Type),
	//						Price:   x.Money,
	//						Title:   x.Memo,
	//						Dqprice: x.RemainMoney,
	//					}
	//					userpricenewadds = append(userpricenewadds, userpricenewadd)
	//				}
	//			}
	//			data_source.Db.Create(&userpricenewadds)
	//			data_source.Db.Model(&models.User{}).Where("id = ?", user.ID).Update("tongbuxiaofei", 2)
	//		}
	//		if user.Tongbudingdan == 1 {
	//			ordertongbu := models.Orderywdtongbu{
	//				Uid:   user.ID,
	//				Chuli: 1,
	//			}
	//			data_source.Db.Create(&ordertongbu)
	//			data_source.Db.Model(&models.User{}).Where("id = ?", user.ID).Update("tongbudingdan", 2)
	//		}
	//
	//		adduser.Tuisong = 1
	//		ctx.JSON(http.StatusOK, gin.H{
	//			"code":    0,
	//			"error":   0,
	//			"success": 200,
	//			"data":    adduser,
	//			"msg":     "ok",
	//		})
	//		return
	//	}
	//}

}
func UserLoginceshi(ctx *gin.Context) {
	json1 := KDRespBody{}
	ctx.ShouldBind(&json1)
	unionid := json1.Unionid
	var weixin models.YwWeixin
	data_source.OtherDb.Where("unionid = ?", unionid).First(&weixin)
	ctx.JSON(http.StatusOK, gin.H{
		"code":    0,
		"error":   0,
		"success": 200,
		"data":    weixin,
		"msg":     "ok",
	})
	return
}
func Classifyduli(ctx *gin.Context) {

	var weixin []models.Classifyduli
	data_source.Db.Find(&weixin)
	ctx.JSON(http.StatusOK, gin.H{
		"code":    0,
		"error":   0,
		"success": 200,
		"data":    weixin,
		"msg":     "ok",
	})
	return
}
func Userdingyue(openid string) (data Tdingyue) {
	configwxtoken := Accesstokengzhywd()
	resp, err := http.Get("https://api.weixin.qq.com/cgi-bin/user/info?access_token=" + configwxtoken + "&openid=" + openid + "&lang=zh_CN")

	if err != nil {
		fmt.Println(err)
		return
	}
	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	r := Tdingyue{}
	fmt.Println("dingyue----------", string(body))

	//把请求到的结构反序列化到专门接受返回值的对象上面
	err = json.Unmarshal(body, &r)
	if err != nil {
		fmt.Println(err)
	}
	return r

}

type Tdingyue struct {
	Subscribe      int    `json:"subscribe"`
	Openid         string `json:"openid"`
	Language       string `json:"language"`
	SubscribeTime  int    `json:"subscribe_time"`
	Unionid        string `json:"unionid"`
	Remark         string `json:"remark"`
	Groupid        int    `json:"groupid"`
	TagidList      []int  `json:"tagid_list"`
	SubscribeScene string `json:"subscribe_scene"`
	QrScene        int    `json:"qr_scene"`
	QrSceneStr     string `json:"qr_scene_str"`
}

//
//func UserLoginywd(ctx *gin.Context) {
//	json1 := KDRespBody{}
//	ctx.ShouldBind(&json1)
//	code := json1.Code
//	pid := json1.Pid
//
//	open := Accesstoken2(code)
//	//fmt.Println(open)
//	//return
//	openid := open.Openid
//	unionid := open.Unionid
//	if openid == "" {
//		ctx.JSON(http.StatusOK, gin.H{
//			"code":    300,
//			"error":   1,
//			"success": 400,
//			"data":    "on",
//			"msg":     "账号不存在",
//		})
//		return
//	}
//
//	reqip := ctx.ClientIP()
//
//	//data := httpPostFormuser(unionid)
//	var weixin models.YwWeixin
//	data_source.OtherDb.Where("unionid = ?", unionid).First(&weixin)
//	fmt.Println(weixin)
//
//	var user models.User
//	data_source.Db.Where("unionid = ?", unionid).First(&user)
//
//	if weixin.ID == 0 {
//		if user.ID == 0 {
//			weixin := Accesstokengzh(open.Openid, open.AccessToken)
//			adduser := models.User{
//				LoginTime:   time.Now().Unix(),
//				LoginIp:     reqip,
//				Ceshiopenid: openid,
//				CreateTime:  time.Now().Unix(),
//				LoginNum:    1,
//				Logo:        weixin.Headimgurl,
//				Nickname:    weixin.Nickname,
//				Status:      1,
//				Unionid:     unionid,
//				Pid:         pid,
//				Guanlian:    2,
//				Identity:    1,
//				Vip:         1,
//				State:       1,
//				Laiyuan:     2,
//				Iflogin:     2,
//				Bangwowa:    1,
//				Dakefu:      1,
//				Ifbuy:       1,
//			}
//			data_source.Db.Create(&adduser)
//			adduser.Tuisong = 1
//			ctx.JSON(http.StatusOK, gin.H{
//				"code":    0,
//				"error":   0,
//				"success": 200,
//				"data":    adduser,
//				"msg":     "ok",
//			})
//			return
//		} else {
//			upuser := models.User{
//				Ceshiopenid: openid,
//				LoginTime:   time.Now().Unix(),
//				LoginIp:     reqip,
//				Price:       weixin.Money,
//				LoginNum:    user.LoginNum + 1,
//			}
//			data_source.Db.Where("id = ?", user.ID).Updates(upuser)
//			var tuisongshezhi []models.Tuisongshezhi
//			data_source.Db.Where("uid = ?", user.ID).Where("state = 1").Find(&tuisongshezhi)
//			if len(tuisongshezhi) == 0 {
//				user.Tuisong = 1
//			} else {
//				user.Tuisong = 2
//			}
//			ctx.JSON(http.StatusOK, gin.H{
//				"code":    0,
//				"error":   0,
//				"success": 200,
//				"data":    user,
//				"msg":     "ok",
//			})
//			return
//		}
//	} else {
//		if user.ID > 0 {
//			upuser := models.User{
//				Ceshiopenid: openid,
//				LoginTime:   time.Now().Unix(),
//				LoginIp:     reqip,
//				Price:       weixin.Money,
//				LoginNum:    user.LoginNum + 1,
//			}
//			data_source.Db.Where("id = ?", user.ID).Updates(upuser)
//			var tuisongshezhi []models.Tuisongshezhi
//			data_source.Db.Where("uid = ?", user.ID).Where("state = 1").Find(&tuisongshezhi)
//			if len(tuisongshezhi) == 0 {
//				user.Tuisong = 1
//			} else {
//				user.Tuisong = 2
//			}
//
//			var xiaofei []models.YwAccountMoney
//			data_source.OtherDb.Where("account_id = ?", weixin.ID).Find(&xiaofei)
//
//			var userpricenews []models.Userpricenew
//			data_source.Db.Where("uid = ?", user.ID).Find(&userpricenews)
//			var userpricenewadds []models.Userpricenew
//			for _, x := range xiaofei {
//				cunzai := 1
//				for _, u := range userpricenews {
//					if x.Ctime == u.Addtime {
//						cunzai = 2
//					}
//				}
//				if cunzai == 1 {
//					userpricenewadd := models.Userpricenew{
//						Uid:     user.ID,
//						Addtime: x.Ctime,
//						State:   int64(x.Type),
//						Price:   x.Money,
//						Title:   x.Memo,
//						Dqprice: x.RemainMoney,
//					}
//					userpricenewadds = append(userpricenewadds, userpricenewadd)
//				}
//			}
//			data_source.Db.Create(&userpricenewadds)
//			ctx.JSON(http.StatusOK, gin.H{
//				"code":    0,
//				"error":   0,
//				"success": 200,
//				"data":    user,
//				"msg":     "ok",
//			})
//			return
//
//		} else {
//
//			adduser := models.User{
//				LoginTime:   time.Now().Unix(),
//				LoginIp:     reqip,
//				Ceshiopenid: openid,
//				CreateTime:  time.Now().Unix(),
//				LoginNum:    1,
//				Logo:        weixin.Headimgurl,
//				Nickname:    weixin.Nickname,
//				Status:      1,
//				Unionid:     unionid,
//				Phone:       weixin.Mobile,
//				Price:       weixin.Money,
//				Pid:         pid,
//				Guanlian:    2,
//				Identity:    1,
//				Vip:         1,
//				State:       1,
//				Laiyuan:     2,
//				Iflogin:     2,
//				Dakefu:      1,
//				Ifbuy:       1,
//			}
//			data_source.Db.Create(&adduser)
//
//			var xiaofei []models.YwAccountMoney
//			data_source.OtherDb.Where("account_id = ?", weixin.ID).Find(&xiaofei)
//
//			var userpricenews []models.Userpricenew
//			data_source.Db.Where("uid = ?", adduser.ID).Find(&userpricenews)
//			var userpricenewadds []models.Userpricenew
//			for _, x := range xiaofei {
//				cunzai := 1
//				for _, u := range userpricenews {
//					if x.Ctime == u.Addtime {
//						cunzai = 2
//					}
//				}
//				if cunzai == 1 {
//					userpricenewadd := models.Userpricenew{
//						Uid:     adduser.ID,
//						Addtime: x.Ctime,
//						State:   int64(x.Type),
//						Price:   x.Money,
//						Title:   x.Memo,
//						Dqprice: x.RemainMoney,
//					}
//					userpricenewadds = append(userpricenewadds, userpricenewadd)
//				}
//			}
//			data_source.Db.Create(&userpricenewadds)
//
//			adduser.Tuisong = 1
//			ctx.JSON(http.StatusOK, gin.H{
//				"code":    0,
//				"error":   0,
//				"success": 200,
//				"data":    adduser,
//				"msg":     "ok",
//			})
//			return
//		}
//	}
//
//}

const (
	appidywd     = "wxa302f6cf7330d474"
	appsecretywd = "7e77c81653d7f8ea6206a0fb3e834fa8"
)

func Accesstokenywd(code string) (data ResponseOpenid) {
	resp, err := http.Get("https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + appidywd + "&secret=" + appsecretywd + "&code=" + code + "&grant_type=authorization_code")
	//fmt.Println(code)
	if err != nil {
		fmt.Println(err)
		return
	}
	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	r := ResponseOpenid{}
	fmt.Println(string(body))

	//把请求到的结构反序列化到专门接受返回值的对象上面
	err = json.Unmarshal(body, &r)
	if err != nil {
		fmt.Println(err)
	}
	return r
}
func httpPostFormuserlist(page, size string) (data T2) {
	resp, err := http.PostForm("http://ywdnew.suishilian.com/user/userlist",
		url.Values{"page": {page}, "size": {size}})
	if err != nil {
		// handle error
	}
	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		// handle error
	}
	r := T2{}
	//fmt.Println(string(body))

	//把请求到的结构反序列化到专门接受返回值的对象上面
	err = json.Unmarshal(body, &r)
	return r
}
func httpPostFormuser(unionid string) (data T) {
	resp, err := http.PostForm("http://ywdnew.suishilian.com/user/usercx",
		url.Values{"unionid": {unionid}})
	if err != nil {
		// handle error
	}
	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		// handle error
	}
	r := T{}
	fmt.Println(string(body))

	//把请求到的结构反序列化到专门接受返回值的对象上面
	err = json.Unmarshal(body, &r)
	return r
}

type T struct {
	Code int `json:"code"`
	Data struct {
		Id            int     `json:"id"`
		Openid        string  `json:"openid"`
		Nickname      string  `json:"nickname"`
		Headimgurl    string  `json:"headimgurl"`
		Remark        string  `json:"remark"`
		SubscribeTime int     `json:"subscribe_time"`
		City          string  `json:"city"`
		Province      string  `json:"province"`
		Sex           int     `json:"sex"`
		Disabled      int     `json:"disabled"`
		Mobile        string  `json:"mobile"`
		RealName      string  `json:"real_name"`
		Money         float64 `json:"money"`
		Accept        int     `json:"accept"`
		Area          string  `json:"area"`
		Types         string  `json:"types"`
		FreezMoney    int     `json:"freez_money"`
		FreezTime     int     `json:"freez_time"`
		AreaGlobal    int     `json:"area_global"`
		RegTime       int     `json:"reg_time"`
		GroupId       int     `json:"group_id"`
		Isadmin       int     `json:"isadmin"`
		Daynum        int     `json:"daynum"`
		Level         int     `json:"level"`
		Email         string  `json:"email"`
		Subscribe     int     `json:"subscribe"`
		Company       string  `json:"company"`
		Unionid       string  `json:"unionid"`
		MiniOpenid    string  `json:"mini_openid"`
		MiniFirst     int     `json:"mini_first"`
		IsDouble      int     `json:"is_double"`
		Vip           int     `json:"vip"`
		VipEnd        int     `json:"vip_end"`
		Refresh       int     `json:"refresh"`
		AppOpenid     string  `json:"app_openid"`
		AppFirst      int     `json:"app_first"`
		Profession    string  `json:"profession"`
		Address       string  `json:"address"`
		Isweb         int     `json:"isweb"`
		Password      string  `json:"password"`
		Major         string  `json:"major"`
		DelayTime     int     `json:"delay_time"`
		ShopId        int     `json:"shop_id"`
		SingleCharge  int     `json:"single_charge"`
		Memo          string  `json:"memo"`
		RefreshTime   int     `json:"refresh_time"`
		UpdateTime    int     `json:"update_time"`
		Openidapp     string  `json:"openidapp"`
	} `json:"data"`
	Error   int    `json:"error"`
	Msg     string `json:"msg"`
	Success int    `json:"success"`
}

type T2 struct {
	Code int `json:"code"`
	Data []struct {
		Id            int     `json:"id"`
		Openid        string  `json:"openid"`
		Nickname      string  `json:"nickname"`
		Headimgurl    string  `json:"headimgurl"`
		Remark        string  `json:"remark"`
		SubscribeTime int     `json:"subscribe_time"`
		City          string  `json:"city"`
		Province      string  `json:"province"`
		Sex           int     `json:"sex"`
		Disabled      int     `json:"disabled"`
		Mobile        string  `json:"mobile"`
		RealName      string  `json:"real_name"`
		Money         float64 `json:"money"`
		Accept        int     `json:"accept"`
		Area          string  `json:"area"`
		Types         string  `json:"types"`
		FreezMoney    int     `json:"freez_money"`
		FreezTime     int     `json:"freez_time"`
		AreaGlobal    int     `json:"area_global"`
		RegTime       int     `json:"reg_time"`
		GroupId       int     `json:"group_id"`
		Isadmin       int     `json:"isadmin"`
		Daynum        int     `json:"daynum"`
		Level         int     `json:"level"`
		Email         string  `json:"email"`
		Subscribe     int     `json:"subscribe"`
		Company       string  `json:"company"`
		Unionid       string  `json:"unionid"`
		MiniOpenid    string  `json:"mini_openid"`
		MiniFirst     int     `json:"mini_first"`
		IsDouble      int     `json:"is_double"`
		Vip           int     `json:"vip"`
		VipEnd        int     `json:"vip_end"`
		Refresh       int     `json:"refresh"`
		AppOpenid     string  `json:"app_openid"`
		AppFirst      int     `json:"app_first"`
		Profession    string  `json:"profession"`
		Address       string  `json:"address"`
		Isweb         int     `json:"isweb"`
		Password      string  `json:"password"`
		Major         string  `json:"major"`
		DelayTime     int     `json:"delay_time"`
		ShopId        int     `json:"shop_id"`
		SingleCharge  int     `json:"single_charge"`
		Memo          string  `json:"memo"`
		RefreshTime   int     `json:"refresh_time"`
		UpdateTime    int     `json:"update_time"`
		Openidapp     string  `json:"openidapp"`
	} `json:"data"`
	Error   int    `json:"error"`
	Msg     string `json:"msg"`
	Success int    `json:"success"`
}
